package social.hub.impl.jersey.api;

import static social.hub.api.facebook.FacebookConstants.*;

import java.util.ArrayList;
import java.util.List;

import com.sun.jersey.api.client.WebResource;

import social.hub.api.facebook.FacebookApi;
import social.hub.api.facebook.FacebookPost;
import social.hub.api.facebook.FacebookProfile;
import social.hub.api.facebook.util.FacebookPostList;
import social.hub.api.facebook.util.FacebookProfileList;
import social.hub.impl.jersey.util.ResourceFactory;
import social.hub.util.UrlBuilder;

public class JerseyFacebookApi implements FacebookApi {

	private final String	accessToken;

	public JerseyFacebookApi(String accessToken) {
		this.accessToken = accessToken;
	}

	@Override
	public List<FacebookProfile> getFriends() {
		return getFriends(SELF_ID);
	}

	@Override
	public List<FacebookProfile> getFriends(String facebookId) {
		return getFriends(facebookId, "id", "name", "picture");
	}

	@Override
	public List<FacebookProfile> getFriends(String facebookId, String... fields) {

		String url = buildUrl(FRIENDS_URL, facebookId);

		if (fields.length > 0) {

			StringBuilder params = new StringBuilder();

			for (String field : fields) {
				params.append(field).append(",");
			}

			params.deleteCharAt(params.length() - 1);

			url += "fields=" + params;

		}

		FacebookProfileList requestData = getResource(url).get(FacebookProfileList.class);

		return requestData.getData();

	}

	@Override
	public List<FacebookPost> getPosts() {
		return getPosts(SELF_ID);
	}

	@Override
	public List<FacebookPost> getPosts(String facebookId) {

		String url = buildUrl(HOME_URL, facebookId);

		FacebookPostList facebookPostList = getResource(url).get(FacebookPostList.class);

		List<FacebookPost> result = new ArrayList<FacebookPost>();

		for (FacebookPost facebookPost : facebookPostList.getData()) {

			if (facebookPost.getType().equals("status")) {
				result.add(facebookPost);
			}

		}

		return result;

	}

	@Override
	public FacebookProfile getUserProfile() {
		return getUserProfile(SELF_ID);
	}

	@Override
	public FacebookProfile getUserProfile(String facebookId) {

		String url = buildUrl(PROFILE_URL, facebookId);

		return getResource(url).get(FacebookProfile.class);

	}

	@Override
	public void sendDirectMessage(String text, String toFacebookId) {

		String url = buildUrl(FEEDS_URL, toFacebookId);

		String body = "message=" + text;

		getResource(url).post(body);

	}

	@Override
	public void updateStatus(String status) {
		sendDirectMessage(status, SELF_ID);
	}

	private String buildUrl(String baseUrl, String facebookId) {
		return new UrlBuilder(baseUrl).addUrlParan("profileId", facebookId)
				.addQueryParan("access_token", accessToken).toString();
	}

	private WebResource getResource(String url) {
		return ResourceFactory.createResource(url);
	}

}
